# utils/request_util.py
import requests
import os
from requests.adapters import HTTPAdapter
from utils.handle_path import CONF_DIR
from utils.common_util import handle_yaml

class BaseApi:
    def __init__(self, headers=None, timeout=10):
        conf_path = os.path.join(CONF_DIR, 'config.yaml')
        conf_data = handle_yaml(conf_path)
        account = conf_data['account']
        self.s = requests.Session()
        self.s.mount('http://', HTTPAdapter(max_retries=3))
        self.s.mount('https://', HTTPAdapter(max_retries=3))
        self.s.headers = headers
        self.timeout = timeout
        self.url = conf_data['env']['host']

    def get(self, url, params=None):
        full_url = self.url + url
        return self.s.get(full_url, params=params, timeout=self.timeout)

    def post(self, url, data=None, json=None):
        full_url = self.url + url
        if data and json:
            raise ValueError("data 和 json 参数不能同时传入")
        if data is not None:
            return self.s.post(full_url, data=data, timeout=self.timeout)
        elif json is not None:
            return self.s.post(full_url, json=json, timeout=self.timeout)
        else:
            return self.s.post(full_url, timeout=self.timeout)

    def __del__(self):
        self.s.close()
